import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import PhotoDetail from '../views/PhotoDetail.vue'
import AuthorDetail from '../views/AuthorDetail.vue'
import Search from '../views/Search.vue'
import NotFound from '../views/NotFound.vue'
import Contest from '../views/Contest.vue'
import Upload from '../views/Upload.vue'
import store from '../store'

// Admin Components
import AdminPhotos from '../views/admin/Photos.vue'
import AdminUsers from '../views/admin/Users.vue'
import AdminComments from '../views/admin/Comments.vue'
import AdminContestants from '../views/admin/Contestants.vue'

// User Components
import UserProfile from '../views/user/Profile.vue'
import UserPhotos from '../views/user/Photos.vue'
import UserVotes from '../views/user/Votes.vue'
import UserComments from '../views/user/Comments.vue'
import UserLikes from '../views/user/Likes.vue'
import UserCollections from '../views/user/Collections.vue'
import UserWorks from '../views/user/Works.vue'
import UserContest from '../views/user/Contest.vue'

// Contestant Components 
import ContestantProfile from '../views/contestant/Profile.vue'
import ContestantWorks from '../views/contestant/Works.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/home',
    redirect: '/'
  },
  {
    path: '/photos/:id',
    name: 'PhotoDetail',
    component: () => import('../views/PhotoDetail.vue')
  },
  {
    path: '/photo/:id',
    redirect: to => {
      return { path: `/photos/${to.params.id}` }
    }
  },
  {
    path: '/author/:id',
    name: 'AuthorDetail',
    component: AuthorDetail
  },
  {
    path: '/search',
    name: 'Search',
    component: Search
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/upload',
    name: 'Upload',
    component: Upload,
    meta: { requireAuth: true }
  },
  {
    path: '/contest',
    name: 'Contest',
    component: Contest
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue'),
    meta: { requireAuth: true },
    children: [
      {
        path: '',
        redirect: 'profile'
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: UserProfile,
        meta: { requireAuth: true }
      },
      {
        path: 'photos',
        name: 'UserPhotos',
        component: UserPhotos,
        meta: { requireAuth: true }
      },
      {
        path: 'votes',
        name: 'UserVotes',
        component: UserVotes,
        meta: { requireAuth: true }
      },
      {
        path: 'comments',
        name: 'UserComments',
        component: UserComments,
        meta: { requireAuth: true }
      },
      {
        path: 'likes',
        name: 'UserLikes',
        component: UserLikes,
        meta: { requireAuth: true }
      },
      {
        path: 'collections',
        name: 'UserCollections',
        component: UserCollections,
        meta: { requireAuth: true }
      },
      {
        path: 'works',
        name: 'UserWorks',
        component: UserWorks,
        meta: { requireAuth: true }
      },
      {
        path: 'contest',
        name: 'UserContest',
        component: UserContest,
        meta: { requireAuth: true }
      }
    ]
  },
  {
    path: '/contestant',
    name: 'Contestant',
    component: () => import('../views/Contestant.vue'),
    meta: { requireAuth: true, requireContestant: true },
    children: [
      {
        path: 'profile',
        name: 'ContestantProfile',
        component: ContestantProfile,
        meta: { requireAuth: true, requireContestant: true }
      },
      {
        path: 'works',
        name: 'ContestantWorks',
        component: ContestantWorks,
        meta: { requireAuth: true, requireContestant: true }
      }
    ]
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Admin.vue'),
    meta: { requireAuth: true, requireAdmin: true },
    children: [
      {
        path: '',
        redirect: 'statistics'
      },
      {
        path: 'statistics',
        name: 'AdminStatistics',
        component: () => import('../views/admin/Statistics.vue'),
        meta: { requireAuth: true, requireAdmin: true }
      },
      {
        path: 'photos',
        name: 'AdminPhotos',
        component: AdminPhotos,
        meta: { requireAuth: true, requireAdmin: true }
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: AdminUsers,
        meta: { requireAuth: true, requireAdmin: true }
      },
      {
        path: 'comments',
        name: 'AdminComments',
        component: AdminComments,
        meta: { requireAuth: true, requireAdmin: true }
      },
      {
        path: 'contestants',
        name: 'AdminContestants',
        component: AdminContestants,
        meta: { requireAuth: true, requireAdmin: true }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound
  },
  {
    path: '*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// Fix NavigationDuplicated error
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err
    }
  })
}

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  // Get user role - either from dedicated role item or from userInfo
  const storedRole = localStorage.getItem('role') 
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  // Use storedRole if available, otherwise fall back to userInfo.role
  const role = storedRole ? parseInt(storedRole) : userInfo.role
  
  console.log('Navigation guard - path:', to.path, 'role:', role, 'storedRole:', storedRole);

  // Special case for redirecting from Contest to Upload when not logged in
  if (to.path === '/upload' && from.path === '/contest' && !token) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }

  if (to.matched.some(record => record.meta.requireAuth)) {
    if (!token) {
      console.log('No token found, redirecting to login');
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else if (to.matched.some(record => record.meta.requireAdmin)) {
      // Check if user is admin (role === 2)
      if (role !== 2) {
        console.log('Route requires admin but user role is', role, 'redirecting to 404');
        next({
          path: '/404'
        })
      } else {
        console.log('Admin authentication passed, proceeding to', to.path);
        next()
      }
    } else if (to.matched.some(record => record.meta.requireContestant)) {
      // Check if user is contestant (role === 3)
      if (role !== 3) {
        console.log('Route requires contestant but user role is', role, 'redirecting');
        next({
          path: '/user/contest'
        })
      } else {
        console.log('Contestant authentication passed, proceeding to', to.path);
        next()
      }
    } else {
      console.log('General authentication passed, proceeding to', to.path);
      next()
    }
  } else {
    next()
  }
})

export default router 